<template>
  <el-card shadow="never">
    <div class="editor-box">
      <div style="border: 1px solid #ccc">
        <Toolbar
          style="border-bottom: 1px solid #ccc"
          :editor="editorRef"
          :defaultConfig="toolbarConfig"
          :mode="mode"
        />
        <Editor
          style="height: 300px"
          v-model="valueHtml"
          :defaultConfig="editorConfig"
          :mode="mode"
          @onCreated="handleCreated"
        />
      </div>
    </div>
  </el-card>
</template>

<script setup name="MyEditor">
import '@wangeditor/editor/dist/css/style.css' // 引入 css

import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { onBeforeUnmount, ref, shallowRef, computed } from 'vue'

const emits = defineEmits(['update:modelValue'])
const props = defineProps(['modelValue'])

const mode = ref('simple')
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

const valueHtml = computed({
  get() {
    return props.modelValue
  },
  set(value) {
    emits('update:modelValue', value)
  },
})

const toolbarConfig = {
  excludeKeys: ['group-video', 'insertVideo'],
}
const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage: {
      server: import.meta.env.VITE_SERVE + '/file/upload',
      base64LimitSize: 5 * 1024, // 5kb
      customInsert(res, insertFn) {
        if (res.code == 200) {
          let url = import.meta.env.VITE_SERVE + '/upload/' + res.file
          insertFn(url, res.file)
        }
      },
    },
  },
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return

  editor.destroy()
})

const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}
</script>

<style lang="scss" scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .comment-cout {
    color: rgba(0, 0, 0, 0.85);
    font-weight: 500;
    font-size: 16px;
  }
}

.editor-box {
  display: flex;

  .editor-avatar {
    margin-right: 10px;
  }
}
p {
  word-wrap: break-word;
}
</style>
